from datetime import datetime, timedelta
import time
from os import abort

from info import db
from info.utils.constants import ADMIN_USER_PAGE_MAX_COUNT, ADMIN_NEWS_PAGE_MAX_COUNT, QINIU_DOMIN_PREFIX
from info.modules.admin import admin_blu
from flask import Flask, request, g, render_template, jsonify, current_app, url_for, redirect, session
from info.utils.response_code import RET, error_map
from info.utils.models import User, News, Category
from info.utils.common import upload_file


# login界面
@admin_blu.route('/login', methods=["POST", "GET"])
def login():
    # ＧＥＴ请求界面
    is_admin = session.get("is_admin")
    if is_admin:
        return redirect(url_for("admin.index"))
    if request.method == "GET":
        return render_template("admin/login.html")

    # ｐｏｓｔ提交参数
    # 获取参数
    username = request.form.get("username")
    password = request.form.get("password")

    # 校验参数
    if not all([username, password]):
        return render_template("admin/login.html", errormsg="参数不全")

    # 校验账户存在及权限
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except BaseException as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errormsg="数据库查询失败")

    if not user:
        return render_template("admin/login.html", errormsg="管理员不存在")

    # 校验密码
    if user.check_passoword(password) == False:
        return render_template("admin/login.html", errormsg="账户或密码错误")

    # 返回控制页面
    session["user_id"] = user.id
    session["is_admin"] = True
    return redirect(url_for("admin.index"))


@admin_blu.route('/index')
def index():
    return render_template("admin/index.html")


# 登出功能
@admin_blu.route('/logout')
def logout():
    session.pop("user_id", None)
    session.pop("is_admin", None)
    return redirect(url_for("admin.login"))


# 统计功能
@admin_blu.route('/user_count')
def user_count():
    # 总人数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except BaseException as e:
        current_app.logger.error(e)

    # 月新增人数
    mon_count = 0
    # 注册时间大于本月１号０点

    # 获取当前时间
    t = time.localtime()

    # 构建目标时间格式
    mon_data_str = "%d-%02d-01" % (t.tm_year, t.tm_mon)
    # 转化成日期格式
    mon_data = datetime.strptime(mon_data_str, "%Y-%m-%d")

    try:
        mon_count = User.query.filter(User.is_admin == False, User.create_time > mon_data).count()
    except BaseException as e:
        current_app.logger.error(e)

    # 日新增人数
    # 注册时间大于本日０点小于次日零点
    day_count = 0
    # 获取当前时间
    t = time.localtime()

    # 构建目标时间格式
    day_date_str = "%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    # 转化成日期格式
    beginday_date = datetime.strptime(day_date_str, "%Y-%m-%d")
    endday_date = beginday_date + timedelta(days=1)

    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time > beginday_date,
                                      User.create_time < endday_date).count()
    except BaseException as e:
        current_app.logger.error(e)

    # 获取每日的注册人数
    active_count = []
    active_time = []

    # 获取当日零点到次日零点的日期对象
    for x in range(0, 30):
        begin_date = beginday_date - timedelta(days=x)
        end_date = beginday_date + timedelta(days=1)
        try:
            one_day_count = User.query.filter(User.is_admin == False, User.create_time > begin_date,
                                              User.create_time < end_date).count()

            active_count.append(one_day_count)

            one_day_str = begin_date.strftime("%Y-%m-%d")
            active_time.append(one_day_str)
        except BaseException as e:
            current_app.logger.error(e)

    active_count.reverse()
    active_time.reverse()

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_count": active_count,
        "active_time": active_time

    }
    return render_template("admin/user_count.html", data=data)


@admin_blu.route('/user_list')
def user_list():
    # 获取参数
    p = request.args.get("p", 1)
    # 校验参数
    try:
        p = int(p)
    except BaseException as e:
        return abort(403)

    # 数据库行为
    try:
        pn = User.query.paginate(p, ADMIN_USER_PAGE_MAX_COUNT)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)
    data = {
        "user_list": [user.to_admin_dict() for user in pn.items],
        "cur_page": pn.page,
        "total_page": pn.pages
    }
    return render_template("admin/user_list.html", data=data)


# 带审核列表
@admin_blu.route('/news_review')
def news_review():
    # 获取参数
    p = request.args.get("p", 1)
    keyword = request.args.get("keyword")
    # 校验参数
    try:
        p = int(p)
    except BaseException as e:
        return abort(403)

    # 数据库行为
    filter_list = []
    if keyword:
        filter_list.append(News.title.contains(keyword))
    try:
        pn = News.query.filter(*filter_list).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)
    data = {
        "news_list": [news.to_review_dict() for news in pn.items],
        "cur_page": pn.page,
        "total_page": pn.pages
    }
    return render_template("admin/news_review.html", data=data)


# 新闻审核详情
@admin_blu.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    # 根据ＩＤ查询新闻
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        return abort(500)
    return render_template("admin/news_review_detail.html", news=news.to_dict())


# 新闻审核
@admin_blu.route('/news_review_action', methods=["POST"])
def news_review_action():
    # 获取和校验参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    reason = request.json.get("reason")
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    try:
        news_id = int(news_id)
    except BaseException as e:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    # 根据action修改新闻状态
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    if action == "accept":
        news.status = 0
    else:
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
        news.reason = reason
        news.status = -1

    # 返回json结果
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 带审核列表
@admin_blu.route('/news_edit')
def news_edit():
    # 获取参数
    p = request.args.get("p", 1)
    keyword = request.args.get("keyword")
    # 校验参数
    try:
        p = int(p)
    except BaseException as e:
        return abort(403)

    # 数据库行为
    filter_list = []
    if keyword:
        filter_list.append(News.title.contains(keyword))
    try:
        pn = News.query.filter(*filter_list).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)
    data = {
        "news_list": [news.to_review_dict() for news in pn.items],
        "cur_page": pn.page,
        "total_page": pn.pages
    }
    return render_template("admin/news_edit.html", data=data)


@admin_blu.route('/news_edit_detail')
def news_edit_detail():
    # 获取和校验参数
    news_id = request.args.get("news_id")
    try:
        news_id = int(news_id)
    except BaseException as e:
        return abort(403)

    # 查询新闻数据
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)
    # 查询分类数据
    try:
        categories = Category.query.filter(Category.id != 1).all()
    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)
    # 标识新闻当前的分类
    category_list = []
    for category in categories:
        category_dict = category.to_dict()
        is_selected = False

        if category.id == news.category_id:
            is_selected = True
        category_dict["is_selected"] = is_selected

        category_list.append(category_dict)
    # 模板渲染
    return render_template("admin/news_edit_detail.html", news=news.to_dict(), category_list=category_list)


@admin_blu.route('/news_edit_detail', methods=['POST'])
def news_edit_detail_post():
    # 获取和校验参数
    news_id = request.form.get("news_id")
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")

    # 注意图片不一定修改
    if not all([news_id, title, category_id, digest, content]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    try:
        news_id = int(news_id)
        category_id = int(category_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET, errmsg=error_map[RET])
    # 数据库行为: 修改新闻的数据
    news.category_id = category_id
    news.title = title
    news.content = content
    news.digest = digest
    if index_image:
        try:
            img_bytes = index_image.read()
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET])
        try:
            file_name = upload_file(img_bytes)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg=error_map[RET.THIRDERR])
        news.index_image_url = QINIU_DOMIN_PREFIX + file_name

    # 返回json
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])
    # 注意: 设置详情模板中的news_id, 用于构建请求参数

@admin_blu.route('/news_type',methods = ["GET","POST"])
def news_type():
# 业务逻辑
# 查询所有分类数据
# 模板渲染

    # GET
    if request.method == 'GET':
        try:
            categories = Category.query.filter(Category.id != 1).all()
        except BaseException as e:
            current_app.logger.error(e)
            return abort(500)
        return render_template("admin/news_type.html",categories = categories)

    name = request.json.get("name")
    id = request.json.get("id")
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if id:
        try:
            id = int(id)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
        try:
            category= Category.query.get(id)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
        category.name = name

    else:
        new_category =  Category(name = name)
        db.session.add(new_category)
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])
            